import { Upload, Button, message } from "antd";
import { UploadOutlined } from "@ant-design/icons";
import type { UploadProps } from "antd";
import { useCallback, useState } from "react";
import { useEffect, useRef } from "react";
import type {
  RcFile,
  UploadFile,
  UploadChangeParam,
} from "antd/es/upload/interface";

export default (props) => {
  const { value = [], onChange, ...other } = props;
  const [fileList, setFileList] = useState();
  const firstRef = useRef(true);
  useEffect(() => {
    if (value?.length && firstRef.current) {
      firstRef.current = false;
      const list = value.map((item, index) => {
        return {
          uid: index,
          name: item,
          status: "done",
          url: item,
        };
      });
      setFileList([...(list || [])]);
    }
  }, [value]);
  useEffect(() => {
    if (fileList?.length) {
      console.log("fileList", fileList);
      let result: Array<String> = [];
      fileList.forEach((item) => {
        const { code, data } = item?.response || {};
        if (item?.status === "done") {
          result.push(data?.url || item?.url);
        }
      });
      onChange?.(result);
    } else {
      onChange?.([]);
    }
  }, [fileList]);
  const config: UploadProps = {
    name: "file",
    action: "/api/upload",
    // headers: {
    //   authorization: 'authorization-text',
    // },
    fileList,
    onChange: (info: UploadChangeParam<UploadFile<any>>) => {
      const { code, data } = info?.file?.response || {};
      if (info?.file?.status === "done" && code === 0 && data) {
        message.success(`${info.file.name} file uploaded successfully`);
      } else if (info?.file?.status === "error") {
        message.error(`${info.file.name} file upload failed.`);
      }
      setFileList([...info?.fileList]);
    },
  };

  return (
    <Upload {...config} {...other}>
      <Button icon={<UploadOutlined />}>Upload</Button>
    </Upload>
  );
};
